package com.lt.accesscontrolmanager.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lt.accesscontrolmanager.domain.Building;
import com.lt.accesscontrolmanager.mapper.BuildingMapper;
import com.lt.accesscontrolmanager.service.BuildingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class BuildingServiceImpl extends ServiceImpl<BuildingMapper, Building> implements BuildingService {

    @Autowired
    BuildingMapper buildingMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public List<Building> selectData() {
        // Redis的key
        String redisKey = "buildings";

        // 尝试从Redis中获取数据
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String buildingsJson = ops.get(redisKey);

        if (buildingsJson != null) {
            return JSON.parseObject(buildingsJson, new TypeReference<List<Building>>() {});
        } else {
            // 如果Redis中没有数据，查询数据库
            List<Building> buildings = buildingMapper.selectList(null);

            // 将查询结果存入Redis，并设置过期时间，例如30分钟
            if (buildings != null) {
                stringRedisTemplate.opsForValue().set(redisKey, JSON.toJSONString(buildings), 30, TimeUnit.MINUTES);
            }

            // 返回查询结果
            return buildings;
        }
    }


}
